package tv.youxing.android.ui;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.HomeModel;
import tv.youxing.android.entity.VideoPlayerPostModel;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.ListPageUtil;

/**
 * Created by Administrator on 2017/8/3.
 * 首页热门视频更多 - 从前面传值
 */

public class HomeFragmentVideoMoreActivity extends BaseActivity {

    @BindView(R.id.pull_refresh_grid)
    PullToRefreshGridView mPullRefreshListView;

    private List<HomeModel.ResultBean.PopularVideoBean.ContListBean> mAllDatas = new ArrayList<>();
    private List<HomeModel.ResultBean.PopularVideoBean.ContListBean> listdatas = new ArrayList<>();
    private  int refCount=0;

    boolean isRef=true;

    private Adapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homefragmentvideomore);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Intent intentGet = getIntent();
        mAllDatas = (List<HomeModel.ResultBean.PopularVideoBean.ContListBean>) intentGet.getSerializableExtra("data");



        initAdapter();
        getData();
    }


    void initAdapter() {
        mAdapter = new Adapter(this, listdatas);
        mPullRefreshListView.setAdapter(mAdapter);
        mPullRefreshListView
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<GridView>()
                {
                    @Override
                    public void onRefresh(
                            PullToRefreshBase<GridView> refreshView)
                    {
                        String label = DateUtils.formatDateTime(
                                getApplicationContext(),
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);
                        // 显示最后更新的时间
//                        refreshView.getLoadingLayoutProxy()
//                                .setLastUpdatedLabel(label);

                        // 模拟加载任务
                        new GetDataTask().execute();
                    }
                });
        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HomeModel.ResultBean.PopularVideoBean.ContListBean m = mAllDatas.get(i);
                VideoPlayerPostModel model = new VideoPlayerPostModel();
                model.setMultimedia_id(m.getMultimedia_id());
                model.setTitle(m.getTitle());
                model.setIntro(m.getIntro());
                model.setCover(m.getCover());
                model.setDuration(m.getDuration());
                model.setPublish_at(m.getPublish_at());
                model.setPlay_url(m.getPlay_url());
                model.setType(m.getType());
                model.setPlay_count(m.getPlay_count());
                model.setComment_count(m.getComment_count());
                model.setLike_count(m.getLike_count());
                model.setCollection_count(m.getCollection_count());
                model.setStatus(m.getStatus());
                model.setCreated_at(m.getCreated_at());
                model.setUpdated_at(m.getUpdated_at());
                model.setIs_like(m.getIs_like());
                model.setIs_collectied(m.getIs_collectied());
                model.setVideo_share_url(m.getVideo_share_url());
                VideoPlayerPostModel.AlbumBean albumBean = new VideoPlayerPostModel.AlbumBean();
                albumBean.setAlbum_id(m.getAlbum().getAlbum_id());
                albumBean.setName(m.getAlbum().getName());
                albumBean.setCover(m.getAlbum().getCover());
                albumBean.setIs_order(m.getAlbum().getIs_order());
                model.setAlbum(albumBean);

                Intent intent = new Intent(HomeFragmentVideoMoreActivity.this, SubscribeDeteilsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data",model);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }



    void getData() {

        if (!isRef){
            return;
        }

        refCount++;
//                fenye(datas,6);
        List<List<HomeModel.ResultBean.PopularVideoBean.ContListBean>> list = Arrays.asList(mAllDatas);
        //数据源,请求的页数,每页返回的条数
        ListPageUtil<HomeModel.ResultBean.PopularVideoBean.ContListBean> listPageUtil = new ListPageUtil<HomeModel.ResultBean.PopularVideoBean.ContListBean>(list.get(0),refCount, 6);
        List<HomeModel.ResultBean.PopularVideoBean.ContListBean> pagedList = listPageUtil.getPagedList();
        if (pagedList.size()<1) {
            CustomToast.INSTANCE.showToast("没数据了");
            isRef=false;
//            refCount=0;
//            listdatas.clear();
//            getData();
            return;
        }
        listdatas.addAll(pagedList);
        mAdapter.notifyDataSetChanged();

//
//
//        for (int i = 0; i < pagedList.size(); i++) {
//            System.out.println(pagedList.get(i).getTitle());
//
//
//
//        }
    }



    private void initIndicator()
    {
        ILoadingLayout startLabels = mPullRefreshListView
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("你可劲拉，拉...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("好嘞，正在刷新...");// 刷新时
        startLabels.setReleaseLabel("你敢放，我就敢刷新...");// 下来达到一定距离时，显示的提示

        ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("你可劲拉，拉2...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("好嘞，正在刷新2...");// 刷新时
        endLabels.setReleaseLabel("你敢放，我就敢刷新2...");// 下来达到一定距离时，显示的提示
    }


    @Subscribe
    public void onEventMainThread(String event) {
        if (event.equals("home")) {
            L.d("s刷新");
            isRef=true;
            listdatas.clear();
            refCount=0;
            getData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class Adapter extends BaseAdapter {

        private Context context;
        private List<HomeModel.ResultBean.PopularVideoBean.ContListBean> listData = new ArrayList<>();
        private LayoutInflater layoutInflater;


        public Adapter(Context context, List<HomeModel.ResultBean.PopularVideoBean.ContListBean> listData) {
            this.context = context;
            this.listData = listData;
            layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return listData==null || listData.size()==0 ? 0 : listData.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            if (viewHolder==null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.layout_item_video, null);
                viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
                viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }

            ImageLoader.getInstance().displayImage( listData.get(position).getCover(),viewHolder.ivIcon);
            viewHolder.tvName.setText(listData.get(position).getTitle()+ listData.get(position).getMultimedia_id());

            return convertView;
        }


        class ViewHolder{
            private ImageView ivIcon;
            private TextView tvName;
        }
    }
    private class GetDataTask extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException e)
            {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            getData();
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshListView.onRefreshComplete();

        }
    }

}
